import * as echarts from 'echarts'
import fullClose from '@/assets/images/full_close.png'

let BigMapOverlay

function getRegionData() {
  return new Promise((res) => {
    res('hello')
  })
}

//#region
// 因为柱状图覆盖物是通过点击原型覆盖物出现的，所以必然地图已经生成，这里就没有检查BMap的存在
function EchartsOverlay(point, item) {
  this._point = point
  this._item = item
}

EchartsOverlay.prototype = new window.BMap.Overlay()

EchartsOverlay.prototype.initialize = function (map) {
  this._map = map
  // var echartsBarbox = $('<div class="echartsBarbox"><img src="../../images/full_close.png"
  // alt="" class="full_close"><div id="echartsBar" style="width: 300px;height: 260px;"></div></div>')
  let echartsBarbox = document.createElement('div')
  let img = document.createElement('img')
  img.src = fullClose
  img.alt = ''
  img.className = 'full_close'

  echartsBarbox.appendChild(img)
  let divEchartsBar = document.createElement('div')
  divEchartsBar.id = 'echartBar'
  divEchartsBar.style.width = '300px'
  divEchartsBar.style.height = '260px'

  echartsBarbox.appendChild(divEchartsBar)

  map.getPanes().markerPane.append(echartsBarbox)

  let param = {}
  if (this._item.province) {
    param = {}
    param.province = this._item.province
  }
  if (this._item.city) {
    param = {}
    param.city = this._item.city
  }
  if (this._item.district) {
    param = {}
    param.city1 = this._item.city
    param.district = this._item.district
  }

  getRegionData(param).then(function (res) {
    if (res.code == 1) {
      let resData = res.result
      if (resData.plugUsage == '') {
        resData.plugUsage = '0'
      }
      let data = [
        parseInt(resData.biiCount),
        parseInt(resData.duration / 60),
        parseInt(resData.electricity),
        parseInt(resData.plugUsage),
        parseInt(resData.money),
      ]
      let max = 100
      for (let i = 0; i < data.length; i++) {
        if (max < data[i]) {
          max = data[i]
        }
        max = Math.ceil(max)
      }
      let echartsBar = echarts.init(document.getElementById('echartsBar'))
      let option = {
        xAxis: [
          {
            type: 'category',
            data: ['订单数', '充电时长', '耗电量', '插口利用率', '消费金额'],
            axisLabel: {
              color: '#8B8B8B',
              fontSize: 10,
              rotate: 45,
            },
            axisTick: {
              show: false,
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#3C66F6',
              },
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
            axisLabel: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            splitLine: {
              lineStyle: {
                color: '#2e4ba4',
                opacity: '0.4',
              },
            },
          },
        ],
        series: [
          {
            // For shadow
            type: 'bar',
            itemStyle: {
              color: '#0F131F',
              barBorderRadius: [5, 5, 0, 0],
            },
            barGap: '-100%',
            barCategoryGap: '10%',
            barWidth: 20,
            data: [max, max, max, max, max],
            silent: true,
          },
          {
            type: 'bar',
            itemStyle: {
              barBorderRadius: [5, 5, 0, 0],
              color: function (params) {
                let colorList = [
                  '#523564',
                  '#FFDC52',
                  '#FFFF01',
                  '#C7EE52',
                  '#52DC52',
                ]
                let colorList2 = [
                  '#D08D85',
                  '#6D5C14',
                  '#6E7014',
                  '#567114',
                  '#0B6B13',
                ]
                return {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 1,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: colorList[params.dataIndex],
                    },
                    {
                      offset: 1,
                      color: colorList2[params.dataIndex],
                    },
                  ],
                  globalCoord: true,
                }
              },
            },
            barWidth: 20,
            data: data,
            label: {
              show: true,
              position: 'top',
              color: '#fff',
              fontSize: 10,
              formatter: function (params) {
                let danwei = ['个', '小时', 'KWh', '%', '元']
                return params.data + danwei[params.dataIndex]
              },
            },
          },
        ],
      }
      echartsBar.setOption(option)
    }
  })

  this._echartsBarbox = echartsBarbox
  // $('.full_close').click(function() {
  //     var allOverlay = map.getOverlays();
  //     for (var i = 0; i < allOverlay.length; i++) {
  //         $('.circleOverlay').removeClass('circleOverlaySel')
  //         if (!allOverlay[i]._text) {
  //             map.removeOverlay(allOverlay[i]);
  //         }
  //     };
  // });

  img.addEventListener('click', () => {
    let allOverlay = map.getOverlays()
    allOverlay.forEach((dom) => {
      if (
        dom.className.includes('circleOverlay') &&
        dom.className !== 'circleOverlay'
      ) {
        dom.className = 'circleOverlay'
      }

      if (!dom._text) {
        map.removeOverlay(dom)
      }
    })
  })
  return echartsBarbox
}

EchartsOverlay.prototype.draw = function () {
  // 根据地理坐标转换为像素坐标，并设置给容器
  var position = this._map.pointToOverlayPixel(this._point)
  this._echartsBarbox.style.left = position.x + 'px'
  this._echartsBarbox.style.top = position.y + 'px'
}

//#endregion

function getBigMapOverlay() {
  if (BigMapOverlay) return BigMapOverlay

  if (window.BMap?.Overlay) {
    BigMapOverlay = function (point, text, item) {
      this._point = point
      this._length = 80
      this._text = text
      this._item = item
    }

    BigMapOverlay.prototype = new window.BMap.Overlay()
    BigMapOverlay.prototype.initialize = function (map) {
      this._map = map
      // let div = $('<div class="circleOverlay"></div>');
      let div = document.createElement('div')
      div.className = 'circleOverlay'
      // div.attr('title', this._text + "（电站数：" + this._item.stationNum + "，插口数：" + this._item.plugNum + ")");
      div.title =
        this._text +
        '（电站数：' +
        this._item.stationNum +
        '，插口数：' +
        this._item.plugNum +
        ')'
      // div.html("<div class='circleOverlayTop'>" + this._text + "</div><div class='circleOverlayBottom'><p>" + this._item.stationNum + "</p><p>" + this._item.plugNum + "</p></div>")
      div.innerHTML =
        "<div class='circleOverlayTop'>" +
        this._text +
        "</div><div class='circleOverlayBottom'><p>" +
        this._item.stationNum +
        '</p><p>' +
        this._item.plugNum +
        '</p></div>'
      // div.click(function() {
      //     var allOverlay = map.getOverlays();
      //     for (var i = 0; i < allOverlay.length; i++) {
      //         if (!allOverlay[i]._text) {
      //             map.removeOverlay(allOverlay[i]);
      //         }
      //     }
      //     $('.circleOverlay').removeClass('circleOverlaySel');
      //     div.addClass('circleOverlaySel');
      //     var myEcharts = new EchartsOverlay(this._point, this._item);
      //     map.addOverlay(myEcharts);

      // }.bind(this))
      // $(map.getPanes().markerPane).append(div);
      div.addEventListener('click', () => {
        let allOverlay = map.getOverlays()
        for (let i = 0; i < allOverlay.length; i++) {
          // 这里应该是找到之前点击出现的echartsoverlay并删除
          if (!allOverlay[i]._text) {
            map.removeOverlay(allOverlay[i])
          }
        }

        let circles = document.getElementsByClassName('circleOverlay')
        circles.forEach((dom) => {
          // 先把进入选择状态的原型覆盖物置为未选择状态
          if (
            dom.className.includes('circleOverlay') &&
            dom.className !== 'circleOverlay'
          ) {
            dom.className = 'circleOverlay'
          }
        })

        // 被点击的原型覆盖物置为选择状态
        div.className = 'circleOverlay circleOverlaySel'

        let myEcharts = new EchartsOverlay(this._point, this._item)
        map.addOverlay(myEcharts)
      })
      map.getPanes().markerPane.append(div)
      this._div = div
      return div
    }
    BigMapOverlay.prototype.draw = function () {
      var position = this._map.pointToOverlayPixel(this._point)
      this._div.style.left = position.x - this._length / 2 + 'px'
      this._div.style.top = position.y - this._length / 2 + 'px'
    }
  }
}

export default getBigMapOverlay
